#coding=utf-8
from flask import Flask, request, make_response
import json
import time
import traceback

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import socket
socket.setdefaulttimeout(1)

app = Flask(__name__)

# import logging
# log = logging.getLogger('werkzeug')
# log.setLevel(logging.ERROR)

TIMEOUT = 5000

mmacs = ['ec:3d:fd:f9:2f:3b', 'ec:3d:fd:f9:2f:40', 'ec:3d:fd:f9:2f:36']
mmacs_pos = [(0, 0), None, None]
mmacs_pos_temp = [[] for i in xrange(3)]
macs = {}
allpos = []

@app.route('/dsky', methods=['POST'])
def recv_data():
	try:
		para = request.form.get('data');
		data = json.loads(para)
		# open('data.json', 'wb').write(json.dumps(data, ensure_ascii=False, indent=4))
		cur_timestamp = int(time.time() * 1000)
		mmac = data['mmac']
		print mmac
		if mmac in mmacs:
			mmac_index = mmacs.index(mmac)		
			for device in data['data']:
				if device['mac'] not in macs:
					macs[device['mac']] = [(0, 0, 0), (0, 0, 0), (0, 0, 0)]
				macs[device['mac']][mmac_index] = (cur_timestamp, float(device['range']), float(device['rssi']))
		for index in xrange(2):
			mmac = mmacs[index]
			if len(mmacs_pos_temp[index]) == 10:
				continue
			if mmac not in macs:
				continue
			if mmacs[index+1] not in macs:
				continue
			timestamp, range, rssi = macs[mmacs[index+1]][index]
			if timestamp != cur_timestamp:
				continue
			mmacs_pos_temp[index] = q = sorted(mmacs_pos_temp[index] + [range])
			if len(q) > 5:
				avg = sum(q[2:-2]) / len(q[2:-2])
			else:
				avg = sum(q) / len(q)
			if index == 0:
				mmacs_pos[index+1] = (avg, 0)
			else:
				mmacs_pos[index+1] = (0, avg)
		print mmacs_pos
	except:
		traceback.print_exc()
	return "Done"
	
@app.route('/allpos', methods=['GET'])
def getAllpos():
	calcAllpos()
	# return "Done"
	# return json.dumps(allpos, ensure_ascii=False)
	response = make_response(json.dumps(allpos, ensure_ascii=False))
	# response = make_response(open('mock.json', 'rb').read())
	response.headers['Access-Control-Allow-Origin'] = '*'
	return response
	
def calcAllpos():
	try:
		# X1, Y1 = 0, 0 # Must be at zero point
		# X2, Y2 = 1400, 0 # Must be on X axios
		# X3, Y3 = 1540, 630
		
		del allpos[:]
		
		X1, Y1 = 0, 0 # Must be at zero point
		if not mmacs_pos[1]:
			return
		X2, Y2 = mmacs_pos[1]
		
		if not mmacs_pos[2]:
			return
		X3, Y3 = mmacs_pos[2]
		
		# json.dump(macs, file('macs.json', 'w'), ensure_ascii=False, indent=4)
		cur_timestamp = time.time()
		for mac, data in macs.items():
			if all([timestamp+TIMEOUT>cur_timestamp for timestamp, range, rssi in data]):
				x, y, diff = calc(X1, Y1, X2, Y2, X3, Y3, data[0][1], data[1][1], data[2][1])
				allpos.append((x, y, diff, mac))
		# json.dump(allpos, file('allpos.json', 'w'), ensure_ascii=False, indent=4)
	except:
		traceback.print_exc()
	
import random
cnt = [2000]
@app.route('/count', methods=['GET'])
def getCount():
	cur_timestamp = int(time.time() * 1000)
	count = 0
	for data in macs.values():
		for timestamp, range, rssi in data:
			if cur_timestamp - timestamp <= 3000:
				count += 1
	# count = len(filter(lambda x: True if cur_timestamp-timestamp<3000 else False, (for data in macs.values() for timestamp, range, rssi in data)))
	# cnt[0] = cnt[0] + random.random() * 21 - 10
	# count = int(cnt[0])
	response = make_response(json.dumps(count))
	response.headers['Access-Control-Allow-Origin'] = '*'
	return response
	
def calc(X1, Y1, X2, Y2, X3, Y3, d1, d2, d3):
	x = X1 + (d1**2 - d2**2 + X2**2) / 2.0 / X2
	y = Y1 + (d1**2 - d3**2 - x**2 + (x-X3)**2 + Y3**2) / 2.0 / Y3
	diff = (abs(((x-X1)**2+(y-Y1)**2)**0.5 - d1) + abs(((x-X2)**2+(y-Y2)**2)**0.5 - d2) + abs(((x-X3)**2+(y-Y3)**2)**0.5 - d3))
	return (x, y, diff)
	
if __name__ == '__main__':
	app.run(host='0.0.0.0', threaded=True)
	